﻿using System;

using Microsoft.Devices.Sensors;

namespace Coding4Fun.Cannon.Phone.Sensor
{
	public class AccelerometerDataAsyncEventArgs : EventArgs
	{
		public AccelerometerData Data { get; set; }
	}

    public class ConcreteAccelerometer : IDisposable
    {
        private bool _hasStarted; 
        
        private AccelerometerData _data;
        private int _readingInterval;
        private int _intervalCounter;

		private readonly Accelerometer _sensor = new Accelerometer();
		private readonly AccelerometerDataAsyncEventArgs _args = new AccelerometerDataAsyncEventArgs();

        public ConcreteAccelerometer()
        {
			var _sensor = new Accelerometer();
            _sensor.ReadingChanged += sensor_ReadingChanged;
        }

        void sensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            _intervalCounter++;
        	if (_intervalCounter < _readingInterval)
				return;

        	//Use to debug Accelerometer
        	//Logger.WriteLine(String.Format("Accelerometer: {0}", Logger.GetDateTime())); 

        	_data.X = e.X;
        	_data.Y = e.Y;
        	_data.Z = e.Z;
		
        	_args.Data = _data;

        	OnReadingChanged(_args);

        	//reset counter
        	_intervalCounter = 0;
        }

        #region IAccelerometer Members

        public event EventHandler<AccelerometerDataAsyncEventArgs> ReadingChanged;

		public void OnReadingChanged(AccelerometerDataAsyncEventArgs e)
		{
			if (ReadingChanged != null)
				ReadingChanged(this, e);
		}

    	public bool HasStarted()
        {
            return _hasStarted; 
        }

        public void Start()
        {
			Start(1); // fires every time
        }

        public void Start(int readingInterval)
        {
			ResetCounters();
			
			_readingInterval = readingInterval;

			if (_sensor.State != SensorState.Ready)
				return;

			_sensor.Start();
			_hasStarted = true;
        }


        public void Stop()
        {
            if (_sensor.State == SensorState.Ready && _hasStarted)
                _sensor.Stop();
            
            _hasStarted = false;

            //reset values; 
            ResetCounters();
        }

        private void ResetCounters()
        {
            _intervalCounter = 0;
            _readingInterval = 0;
        }

        #endregion

    	#region Implementation of IDisposable

    	public void Dispose()
    	{
			_sensor.Dispose();
    	}

    	#endregion
    }
}
